<?php

namespace app\api\controller\resigter;

use fast\Http;
use think\Config;
use think\Db;
use think\Log;

/**
 * 基础
 */
class Bases
{

	use \app\common\traits\ToolTrait;

	/**
	 * 实例对象
	 * @var object
	 */
	protected static $instance;


	protected $limit_nums = 10000;

	/**
	 * 默认配置
	 * @var array
	 */
	protected $config = [
		"prefix" 		=> "fd_",
		"admin" 		=> "admin",
		"user" 			=> "user",
		"mer"			=> "machine_address",
		"mac"			=> "machine",
		"addr" 			=> "address",
		"card"			=> "user_card",
		"wx" 			=> "user_wechats",
		"mer_sta"		=> "merchant_status"
	];


	/**
	 * 默认架构方法
	 */
	public function __construct()
	{
	}

	/**
	 * 实例化
	 */
	public static function instance()
	{
		if (is_null(self::$instance)) {
			self::$instance = new static();
		}
		return self::$instance;
	}

	/**
	 * 检测客服是否绑定微信
	 */
	public function check_customer_bind_wx($aid, $gid)
	{
		if ($aid && $gid) {
			$finds = Db::name($this->config["user"])
				->where("group_id", $gid)
				->where("admin_id", $aid)
				->count();
			if ($finds) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 检测设备是否绑定
	 */
	public function check_machine_bind($mcode)
	{
		if ($mcode) {
			$where = ["number" => $mcode];
			$finds = Db::name($this->config["mac"])
				->where($where)
				->field("is_bind,is_status")
				->find();
			if ($finds) {
				if ($finds["is_status"] < 3) {
					if ($finds["is_bind"] ==  1) {
						return true;
					}
				}
			}
		}
		return false;
	}

	/**
	 * 查看手机号是否唯一
	 */
	public function check_phone_unique($phone, $typ)
	{
		if (!$phone && !$typ) {
			return false;
		}
		$where = "";
		$where = "mobile = '{$phone}' and is_typs = {$typ}";
		$reutn = true;
		$check = Db::name($this->config["user"])->where($where)->count();
		if ($check) {
			$reutn = false;
		}
		return $reutn;
	}

	/**
	 * 创建-用户
	 */
	public function create_user($regPrams = [], $addrPrams = [])
	{

		if ($regPrams && $addrPrams) {
			$regPrams['jointime'] 	= time();
			$regPrams['createtime'] = time();
			$regPrams['level']		= 1;
			$regPrams['status'] 	= 'normal';
			$regPrams['avatar'] 	= $this->_avatar($regPrams["wx_open_id"]);
			Db::startTrans();
			try {
				$table = $this->config["user"];
				$id = Db::name($table)->insertGetId($regPrams);
				if ($id) {
					$addrPrams["user_id"] = $id;
					$addrPrams["create_time"] = time();
					$ret = Db::name($this->config["addr"])->insert($addrPrams);
					if ($ret) {
						$check = true;
						if ($regPrams["is_typs"] == 1) {
							$this->store_merchant_status($id);
							$addrPrams["number"] = $regPrams["mercode"];
							$bindRet = $this->_machine_binds($addrPrams);
							if (!$bindRet) {
								$check = false;
							}
						}
						if ($check) {
							Db::commit();
							$find = Db::name($table)->field("id,nickname,mobile,wx_open_id")->find($id);
							return $find;
						}
					}
				}
			} catch (\Exception $e) {
				Log::write($e->getMessage());
				Db::rollback();
				return false;
			}
		} else {
			return false;
		}
	}

	/**
	 * 头像存储
	 */
	public function _avatar($opendid)
	{
		$imgs = "/assets/img/avatar.png";
		$find = Db::name($this->config["wx"])->where("openid", $opendid)->find();
		if ($find) {
			$resource = Http::get($find["headimgurl"]);
			$path = "./uploads/user/";
			$this->creDirectory($path);
			$file = $path . date("dMYHis") . rand(100, 999) . ".png";
			file_put_contents($file, $resource);
			$imgs =  substr($file, 1);
		}
		return $imgs;
	}

	/**
	 * 存储 商户状态
	 */
	public function store_merchant_status($uid)
	{
		if ($uid) {
			$data = ["uid" => $uid];
			$check = Db::name($this->config["mer_sta"])
				->where($data)
				->count();
			if (!$check) {
				$data["status"]   = 1;
				$data["reg_time"] = strtotime(date("Y-m-d", time()));
				Db::name($this->config["mer_sta"])->insertGetId($data);
			}
		}
	}

	/**
	 * 商家 身份证正反面、营业执照存储
	 */
	public function merchant_idCard_save($prams)
	{
		if ($prams) {
			$finds = Db::name($this->config["card"])
				->where("sale_id", $prams["sale_id"])
				->count();
			if (!$finds) {
				Db::startTrans();
				try {
					$id = Db::name($this->config["card"])->insertGetId($prams);
					if ($id) {
						Db::commit();
					}
				} catch (\Exception $e) {
					Log::write($e->getMessage());
					Db::rollback();
					return false;
				}
				return true;
			}
		} else {
			return false;
		}
	}

	/**
	 * 创建-客服
	 */
	public function create_customer($regPrams = [])
	{

		if ($regPrams) {
			$finds = Db::name($this->config["admin"])
				->where("id", $regPrams["admin_id"])
				->find();
			if ($finds) {
				$regPrams["nickname"] 	= $finds["nickname"];
				$regPrams["username"] 	= $finds["mobile"];
				$regPrams["mobile"]   	= $finds["mobile"];
				$regPrams["password"] 	= $finds["password"];
				$regPrams["salt"]		= $finds["salt"];
				$regPrams['jointime'] 	= time();
				$regPrams['createtime'] = time();
				$regPrams['level']		= 1;
				$regPrams['status'] 	= 'normal';
				$regPrams['avatar'] 	= $this->_avatar($regPrams["wx_open_id"]);
				Db::startTrans();
				try {
					$table = $this->config["user"];
					$id = Db::name($table)->insertGetId($regPrams);
					if ($id) {
						Db::commit();
						$find = Db::name($table)->field("id,nickname,mobile,wx_open_id")->find($id);
						return $find;
					}
				} catch (\Exception $e) {
					Log::write($e->getMessage());
					Db::rollback();
					return false;
				}
			}
		}
		return false;
	}

	/**
	 * 绑定机器
	 */
	public function _machine_binds($binPrams = [])
	{
		$binPrams["active_time"] = time();
		$ret = Db::name($this->config["mer"])->insert($binPrams);
		if ($ret) {
			$where = "";
			$where = "number = '" . $binPrams["number"] . "'";
			$update = ["is_bind" => 1];
			$req = Db::name($this->config["mac"])->where($where)->update($update);
			if ($req) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 发货地址
	 */
	public function address_id($uid)
	{
		return Db::name($this->config["addr"])->where("user_id", $uid)->where("default", 1)->value("id");
	}

	/**
	 * 商家 ID
	 */
	public function mer_id($mcode)
	{
		return Db::name($this->config["user"])->where("status = 'normal' and mercode = '{$mcode}' and is_typs = 1")->value("id");
	}

	/**
	 * 用户类型
	 */
	public function user_type($uid)
	{
		return Db::name($this->config["user"])->where("id = {$uid}")->value("is_typs");
	}
}
